package uk.ac.shef.ecomm.jdbc.mysql;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import uk.ac.shef.ecomm.*;

public class ParticipantRegisteration extends Registeration
{
	private PreparedStatement sqlInsertLogin;
	private PreparedStatement sqlInsertPart;
	
	public ParticipantRegisteration()
	{
		try
		{
			connect();
			sqlInsertLogin = connection.prepareStatement("INSERT into " + UserTBL + " (email,password,type,last_access) VALUES (?,?,?,NOW())");
			sqlInsertPart = connection.prepareStatement("INSERT into " + ParticipantsTBL + " (email,name,dob,gender,lang,smoker) VALUES (?,?,?,?,?,?)");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}
	public boolean register(Participant p)
	{
		try
		{
			int result;
			
			sqlInsertLogin.setString(1, p.getEmail());
			sqlInsertLogin.setString(2, p.getPass());
			sqlInsertLogin.setString(3, p.getType());
			
			result = sqlInsertLogin.executeUpdate();
		
			if (result == 0)
			{
				connection.rollback();
				return false;
			}
			
			
			sqlInsertPart.setString(1, p.getEmail());
			sqlInsertPart.setString(2, p.getName());
			sqlInsertPart.setDate(3, p.getDOB());
			sqlInsertPart.setString(4, p.getGender());
			sqlInsertPart.setString(5, p.getLanguage());
			sqlInsertPart.setBoolean(6, p.getIsSmoker());
			
			result = sqlInsertPart.executeUpdate();
			if (result == 0)
			{
				connection.rollback();
				return false;
			}
			
			connection.commit();
			return true;
			
		}
		catch (SQLException sqle)
		{
			sqle.printStackTrace();
			return false;
		}	
	}

	public boolean deregister(Participant p)
	{
		// find all projects this participant is in
		// find all time slots for those projects where this participant is in
		// remove his entries
		//TBD: implement it 
		System.out.println("Not yet implemented!");
		return false;
	}
	public void close()
	{
		try
		{
			sqlInsertLogin.close();
			sqlInsertPart.close();;
			connection.close();
		}
		catch (SQLException ex)
		{
			ex.printStackTrace();
		}
	}
}
